<template>
    <div ref="mount" id="mount"></div>
</template>

<script setup>
    import { ref, onMounted, onUnmounted } from "vue"
    import * as THREE from "three"

    // 引用 DOM 容器
    const mount = ref(null)

    // 初始化 three.js 场景、相机和渲染器
    let scene, camera, renderer

    onMounted(() => {
        // 容器宽高
        const width = mount.value.clientWidth
        const height = mount.value.clientHeight

        // 创建场景
        scene = new THREE.Scene()

        // 创建相机
        const aspectRatio = width / height
        const fieldOfView = 75
        const nearPlane = 0.1
        const farPlane = 1000
        camera = new THREE.PerspectiveCamera(
            fieldOfView,
            aspectRatio,
            nearPlane,
            farPlane
        )
        camera.position.z = 5

        // 创建渲染器并添加到 DOM
        renderer = new THREE.WebGLRenderer()
        renderer.setSize(width, height)
        mount.value.appendChild(renderer.domElement)

        // 创建一个简单的几何体并添加到场景中（可选）
        const geometry = new THREE.BoxGeometry(1, 1, 1)
        const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 })
        const cube = new THREE.Mesh(geometry, material)
        scene.add(cube)

        // 渲染循环
        const animate = function () {
            requestAnimationFrame(animate)

            // 这里可以添加动画逻辑
            // ...

            renderer.render(scene, camera)
        }

        animate()
    })

    onUnmounted(() => {
        // 清理
        if (renderer && mount.value) {
            mount.value.removeChild(renderer.domElement)
            renderer = null
            scene = null
            camera = null
        }
    })
</script>

<style scoped>
    /* 设置容器的样式，确保能够正确显示 3D 渲染 */
    #mount {
        width: 100%;
        height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #f0f0f0;
    }
</style>
